package com.longe.nio.chat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Scanner;

public class ChatClient {

    //定义相关的属性
    private final String HOST = "127.0.0.1"; // 服务器的ip
    private final int PORT = 9999; //服务器端口
    private Selector selector;
    private SocketChannel socketChannel;
    private String username;

    public ChatClient(String username) {
        this.username = username;
    }

    //构造器, 完成初始化工作
    public void start() throws IOException {

        selector = Selector.open();
        //连接服务器
        socketChannel = socketChannel.open(new InetSocketAddress(HOST, PORT));
        //设置非阻塞
        socketChannel.configureBlocking(false);
        //将channel 注册到selector
        socketChannel.register(selector, SelectionKey.OP_READ);
        System.err.println(username + " is ok...");

        //接收服务器响应信息
        new Thread(new ChatClientHandler(selector)).start();

        //发送数据给服务器端
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()) {
            String message = scanner.nextLine();
            if (message != null && message.length() > 0) {
                socketChannel.write(Charset.forName("UTF-8").encode(username + " : " + message));
            }
        }

    }

    //读取从服务器端回复的消息
    public void readMessage(SelectionKey key) throws IOException {

        //通过key反向得到相关的通道
        SocketChannel socketChannel = (SocketChannel) key.channel();
        //得到一个Buffer
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        StringBuilder message = new StringBuilder();
        int read;
        while ((read = socketChannel.read(buffer)) > 0) {
            //把缓存区的数据转成字符串
            String msg = new String(buffer.array(), 0, read);
            message.append(msg);
            //复位
            buffer.clear();
        }
        if (message.toString().length() > 0) {
            //输出该消息
            System.err.println(message.toString());
        }

    }

    /**
     * 客户端线程类，专门接收服务器端响应信息
     */
    private class ChatClientHandler implements Runnable {
        private Selector selector;

        public ChatClientHandler(Selector selector) {
            this.selector = selector;
        }

        @Override
        public void run() {

            try {
                while (true) {
                    int count = selector.select();
                    if (count < 1) { //当count > 0 的时候表示有事件要处理
                        System.err.println("没啥事情干, 等待....");
                        continue;
                    }

                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()) {
                        //取出selectionKey
                        SelectionKey key = iterator.next();
                        if (key.isReadable()) {
                            readMessage(key);
                        }
                    }
                    //当前的key 删除，防止重复处理
                    iterator.remove();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}